<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="always">
        <div slot="header" class="clearfix">
          <span>{{ list.id ? '试题修改' :'试题录入' }}</span>
        </div>
        <el-form ref="ruleForm" :model="list" :rules="rules" label-width="120px" class="demo-ruleForm">
          <el-form-item label="学科：" prop="subjectID">
            <el-select v-model="list.subjectID" placeholder="请选择" @change="changeSub">
              <el-option v-for="item in subjects" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="目录：" prop="catalogID">
            <el-select v-model="list.catalogID" placeholder="请选择">
              <el-option v-for="item in ndcategorys" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select v-model="list.enterpriseID" placeholder="请选择">
              <el-option v-for="item in companys" :key="item.id" :label="item.shortName" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="城市：" required>
            <!-- 城市 -->
            <el-col :span="3.5">
              <el-form-item prop="province">
                <el-select v-model="list.province" placeholder="请选择" style="width:198px; " @change="cityChange">
                  <el-option v-for="item in provinces" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
            <!-- 地区 -->
            <el-col :span="11">
              <el-form-item prop="city">
                <el-select v-model="list.city" placeholder="请选择" style="width:198px; margin-left: 4px; ">
                  <el-option v-for="item in citys" :key="item" :label="item" :value="item" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select v-model="list.direction" placeholder="请选择">
              <el-option v-for="(item,index) in directions" :key="index" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="题型：" prop="questionType">
            <template>
              <el-radio-group v-model="list.questionType">
                <el-radio v-for="item in questionTypes" :key="item.value" :label="`${item.value}`" @click="changeQt" @click.native="changeQt">{{ item.label }}</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
          <el-form-item label="难度：" prop="difficulty">
            <template>
              <el-radio-group v-model="list.difficulty">
                <el-radio v-for="item in difficulties" :key="item.value" :label="`${item.value}`">{{ item.label }}</el-radio>
              </el-radio-group>
            </template>
          </el-form-item>
          <el-form-item label="题干：" prop="question">
            <template>
              <!-- 富文本编辑器 -->
              <quill-editor v-model="list.question" :options="editorOption" />
            </template>
          </el-form-item>

          <!-- 选项 -->
        <el-form-item v-if="list.questionType !== '3'" class="options" label="选项：" prop="options">
          <div  class="queType"  v-for="(item,index) in list.options"   :key="item.id"  >
            <el-radio-group v-model="radio" >
              <el-radio
                v-if="list.questionType === '1'"
                  :label="item.code"
                  @click.native="cekRadio(index)"
                >&nbsp;</el-radio>
              <el-checkbox
                  v-else-if="list.questionType === '2'"
                  v-model="item.isRight"
                  :label="true"
                >&nbsp;</el-checkbox>
          </el-radio-group>
            <div style="overflow: hidden;display: inline-block;">{{ item.code }}：<el-input v-model="item.title" style="width:240px" />
                </div>
              <upload-img v-model="item.img" /> <i class="el-icon-circle-close imgClose" @click="delOption(index)" />
            </div>
            <el-button size="small" :disabled="list.questionType === '1'" type="danger" @click="addOption">+增加选项与答案</el-button>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频：" prop="videoURL">
            <el-input v-model="list.videoURL" style="" />
          </el-form-item>

          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <template>
              <!-- 富文本编辑器 -->
              <quill-editor v-model="list.answer" :options="editorOption" />
            </template>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：" prop="remarks">
            <el-input v-model="list.remarks" size="small" type="textarea" />
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="标签：" prop="tags">
            <el-select v-model="list.tags" multiple placeholder="请选择">
              <el-option v-for="item in tags" :key="item.id" :label="item.tagName" :value="item.tagName" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button v-if="list.id" type="success" @click="submitForm('ruleForm')">确认修改</el-button>
            <el-button v-else type="primary" @click="submitForm('ruleForm')">确认提交</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { provinces, citys } from '@/api/hmmm/citys.js'
import { direction, questionType, difficulty, editorOption } from '@/api/hmmm/constants.js'
import { list } from '@/api/hmmm/companys.js'
import { getSubject } from '@/api/hmmm/subjects.js'
import { getNdcategory } from '@/api/hmmm/directorys.js'
import { getTags } from '@/api/hmmm/tags.js'
import { add, update, detail } from '@/api/hmmm/questions'

// 导入富文本依赖
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

// 导入其他组件
import uploadImg from '@/module-hmmm/components/uploadImg.vue'
import { quillEditor } from 'vue-quill-editor'
export default {
  // 注册组件
  components: {
    quillEditor,
    uploadImg
  },
  data () {
    return {
      list: {
        id: undefined, // 题目id
        subjectID: '', // 学科
        catalogID: '', // 二级目录
        tags: '', // 标签
        keyword: '', // 关键字
        questionType: '1', // 试题类型
        difficulty: '1', // 难度
        direction: '', // 方向
        creatorID: '', // 录入人
        remarks: '', // 题目备注
        enterpriseID: '', // 企业id
        province: '', // 城市
        city: '', // 地区
        question: '', // 题干
        videoURL: '', // 视频地址
        answer: '', // 答案解析
        options: [// 选项
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      },
      // 默认选项内容
      // 单选值
      radio: '',
      // 城市数据
      provinces: provinces(),
      // 城市下地区
      citys: [],
      // 方向列表
      directions: direction,
      // 题型列表
      questionTypes: questionType,
      // 难度变量
      difficulties: difficulty,
      // 富文本配置项
      editorOption: editorOption,
      // 企业列表
      companys: [],
      // 学科简单列表
      subjects: [],
      // 二级目录
      ndcategorys: [],
      // 标签
      tags: [],
      // 表单验证规则
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'change' }
        ],
        answer: [
          { required: true, message: '请填写答案解析', trigger: 'blur' }
        ],
        tags: [
          { required: true, message: '请选择标签', trigger: 'blur' }
        ]
      }
    }
  },
  async created () {
    // 通过获取路由参数的id是否存在 判断当前页是修改还是刷新
    this.list.id = this.$route.query.id
    // 页面刷新调用方法获取企业列表
    this.getCompanyList()
    // 获取学科列表
    this.subjects = await getSubject()
    // 如果是修改 则回显数据
    if (this.list.id) {
      // 获取回显数据
      await this.getQuestionDetail(this.list.id)
      // 获取标签列表
      this.tags = await getTags(this.list.subjectID)
      // 变更标签格式
      this.list.tags = this.list.tags.split(',')
      // 回显选中状态
      this.list.options.forEach(item => {
        if (item.isRight) this.radio = item.code
      })
    }
  },
  methods: {
    // 提交表单
    submitForm (formName) {
      this.$refs[formName].validate(async (valid) => {
        // 判断校验
        if (!valid) return this.$message.error('请按规范填写数据')
        // 校验通过
        // 变更标签格式
        this.list.tags = this.list.tags.join(',')
        if (this.list.id) {
          // 编辑操作
          await update(this.list)
          this.$message.success('修改成功')
          this.$router.push('/questions/choice')
        } else {
          await add(this.list)
          this.$message.success('添加成功')
          this.$router.push('/questions/list')
        }
      })
    },
    // 单选框切换
    cekRadio (val) {
      // 重置选项
      this.changeQt()
      // 选中
      this.list.options[val].isRight = true
    },
    // 重置选项
    changeQt () {
      this.list.options.forEach(item => { item.isRight = false })
    },
    // 重置表单
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    // 获取企业列表
    async getCompanyList () {
      const { data: res } = await list({ pagesize: 10000 })
      this.companys = res.items
    },
    // 获取题目详情
    async getQuestionDetail (id) {
      const { data: res } = await detail({ id })
      this.list = res
      // 选项重排序
      this.list.options = this.list.options.sort((a, b) => {
        return a.code.charCodeAt(0) - b.code.charCodeAt(0)
      })
      this.list.options.forEach(item => { item.isRight = !!item.isRight })
      this.tags = this.list.tags.split(',')
    },
    // 城市变更
    cityChange () {
      // 清空地区数据
      this.list.city = ''
      // 获取地区列表
      this.citys = citys(this.list.province)
    },
    // 学科变更
    async changeSub () {
      // 清空学科联动数据
      this.list.catalogID = undefined
      this.list.tags = undefined
      // console.log('旧值:', oldValue, '; 新值:', newValue)
      // 调用方法 获取二级目录
      this.ndcategorys = await getNdcategory(this.list.subjectID)
      // 调用方法 获取标签
      this.tags = await getTags(this.list.subjectID)
    },
    // 增加选项
    addOption () {
      // 这一步是关键，灵活使用Unicode编码，首先获取A的编码，然后增加已有编号的长度，再转换为字母
      // 如果编码不是从A开始，就把'A'.charCodeAt(0)中的A替换成起始字母
      const code = String.fromCharCode('A'.charCodeAt(0) + this.list.options.length)
      // 上面的code就是下一步要增加的序号
      this.list.options.push({ isRight: false, code, title: '', img: '' })
    },
    // 删除选项
    delOption (val) {
      // 判断 小于等于4个选项 不让删除.
      if (val <= 3) {
        console.log(this.list.options[val])
        this.list.options[val].img = ''
        // console.log(this.list.options[val])
        return
      }
      // 大于四个选项 删除
      this.list.options.splice(val)
    }

  }

}
</script>

<style lang="scss" scoped>
  .demo-ruleForm {
    .el-select,.el-input,.el-textarea{
      width: 400px;
      ::v-deep .el-textarea__inner {
          height: 96px;
        }
    }
  }
  .queType {
    display: block;
    height: 80px;
    padding: 0 0 20px;
    line-height: 60px;

    .imgClose {
        position: relative;
        cursor: pointer;
        left: -8px;
        top: -53px;
        font-size: 18px;
        color: rgba(2, 2, 2, 0.306);
      }

  ::v-deep  .el-radio-group {
            margin-top: -52px;
          }

  }
  ::v-deep .el-checkbox.queType {
    display: flex;
    align-items: center;
  }
::v-deep .ql-editor {
    height: 200px;
  }

::v-deep .ql-toolbar.ql-snow {
  height: 38px;
  line-height: 1.0;
}
  .avatar-uploader{
    display: inline-block;
    width: 100px;
    height: 60px;
    line-height: 60px;

  }

</style>
